<template>
  <div class="login-container">
    <div class="login-box">
      <h2>管理员登录</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef"> 
        <!-- ref="loginFormRef" 表示表单的引用,用于获取表单实例 -->
        <el-form-item prop="adminName">
          <el-input
            v-model="loginForm.adminName"
            placeholder="请输入管理员账号"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin" style="width: 100%">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '@/api/user'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const loading = ref(false)
const loginFormRef = ref()
const userStore = useUserStore()

const loginForm = reactive({
  adminName: '',
  password: ''
})

const rules = {
  adminName: [
    { required: true, message: '请输入管理员账号', trigger: 'blur' } // required: true 表示必填项,message: '请输入管理员账号' 表示错误提示信息,trigger: 'blur' 表示在失去焦点时触发验证
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' } // 密码不能为空
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        const success = await userStore.login(loginForm.adminName, loginForm.password)
        
        if (success) {
          ElMessage.success('登录成功')
          router.push('/')
        } else {
          ElMessage.error('登录失败，请检查用户名和密码')
        }
      } catch (error) {
        console.error('登录错误详情:', error)
        ElMessage.error(error.response?.data?.msg || '登录失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-box h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}
</style> 